package se.webbzon.boltzmann.timer;

import java.util.ArrayList;
import java.util.Collection;

import se.webbzon.boltzmann.debug.Debug;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldobject.WorldObject;

public class Timer extends WorldObject {
	
	// A collection of all listeners to this timer
	private final Collection<TimerListener> listeners;
	
	// The startup time for the timer
	private final int time;
	
	// The remaining time for the timer
	private int remaining;
	
	/*============================================================
	Constructors
	============================================================*/

	public Timer(int time) {
		super(WorldObject.onCreate + WorldObject.onStep);
		this.listeners = new ArrayList<TimerListener>();
		this.time = time;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Starts the timer in the given world. **/
	public void start(WorldArea world) {
		world.createInstance(this);
	}
	
	/** Returns the startup time for this timer. **/
	public int getStartupTime() {
		return time;
	}
	
	/** Returns the remaining time for this timer. **/
	public int getTime() {
		return remaining;
	}
	
	/** Adds a listener to this timer. **/
	public boolean addListener(TimerListener listener) {
		int d;
		Debug.debugCollection(this, listeners);
		return listeners.add(listener);
	}
	
	/** Removes a listener from this timer. **/
	public boolean removeListener(TimerListener listener) {
		return listeners.remove(listener);
	}
	
	/** Clears all listeners from this timer. **/
	public void clearListener(TimerListener listener) {
		listeners.clear();
	}

	@Override public void onCreate(WorldArea world) {
		remaining = time;
	}
	
	@Override public void onStep(WorldArea world) {
		if (remaining == 0) {
			for (TimerListener listener : listeners)
				listener.onAlarm(this);
			world.destroyInstance(this);
		} else
			remaining--;
	}

}
